import { _decorator, AudioClip, AudioSource, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('AudioManager')
export class AudioManager extends Component {
    public static instance:AudioManager;

    @property(AudioClip)
    public clips:AudioClip[] = [];

    private tracks:AudioSource[]= [];

    private audios:Map<string,AudioClip>;
    private source:AudioSource;
    
    protected onLoad(): void {
        AudioManager.instance = this;
        this.source = this.node.getComponent(AudioSource);
        this.audios = new Map<string,AudioClip>();
        this.clips.forEach(element => {
            console.log(element.name);
            this.audios.set(element.name,element);
        });

        this.tracks = this.node.getComponentsInChildren(AudioSource);
    }
    
    public playOneShot(name:string,track:number = -1){
        if(!this.audios.has(name))return;
        if(track == -1){
            this.source.playOneShot(this.audios.get(name));
        }
        else {
            this.tracks[track].playOneShot(this.audios.get(name));
        }
    }

    public play(name:string,track:number = -1){
        if(!this.audios.has(name))return;
        var source = this.source;
        if(track != -1){
            source = this.tracks[track];
        }

        var oldClip = source.clip;
        var newClip = this.audios.get(name);
        if(oldClip == newClip){
            if(source.playing){

            }
            else{
                source.clip = newClip;
                source.play();
            }
        }
        else{
            source.clip = newClip;
            source.play();
        }
    }

    public stop(track:number = -1){
        var source = this.source;
        if(track != -1){
            source = this.tracks[track];
        }
        source.stop();
    }
}


